<!DOCTYPE html>





<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/CNY32x32.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/CNY16x16.png?v=7.3.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":true},
    save_scroll: false,
    copycode: {"enable":true,"show_result":true,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="前言Scrapy是一个为了爬取网站数据，提取结构性数据而编写的应用框架。 其可以应用在数据挖掘，信息处理或存储历史数据等一系列的程序中。其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的， 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛，可以用于数据挖掘、监测和自动化测试。 具体可查看文档">
<meta name="keywords" content="爬虫">
<meta property="og:type" content="article">
<meta property="og:title" content="Scrapy爬取CSDN博客列表">
<meta property="og:url" content="localhost:4000/2019/08/16/Scrapy爬取CSDN博客列表/index.html">
<meta property="og:site_name" content="钟浩伟的个人博客">
<meta property="og:description" content="前言Scrapy是一个为了爬取网站数据，提取结构性数据而编写的应用框架。 其可以应用在数据挖掘，信息处理或存储历史数据等一系列的程序中。其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的， 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛，可以用于数据挖掘、监测和自动化测试。 具体可查看文档">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816235500.png!blog">
<meta property="og:image" content="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816135546.png!blog">
<meta property="og:image" content="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816140048.png!blog">
<meta property="og:image" content="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816145051.png!blog">
<meta property="og:image" content="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816145728.png!blog">
<meta property="og:updated_time" content="2019-08-16T15:57:36.328Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Scrapy爬取CSDN博客列表">
<meta name="twitter:description" content="前言Scrapy是一个为了爬取网站数据，提取结构性数据而编写的应用框架。 其可以应用在数据挖掘，信息处理或存储历史数据等一系列的程序中。其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的， 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛，可以用于数据挖掘、监测和自动化测试。 具体可查看文档">
<meta name="twitter:image" content="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816235500.png!blog">
  <link rel="canonical" href="localhost:4000/2019/08/16/Scrapy爬取CSDN博客列表/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Scrapy爬取CSDN博客列表 | 钟浩伟的个人博客</title>
  








  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">钟浩伟的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">欢迎光临</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    
  <div class="popup search-popup">
  <div class="search-header">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <div class="search-input-wrapper">
      <input autocomplete="off" autocorrect="off" autocapitalize="none"
             placeholder="搜索..." spellcheck="false"
             type="text" id="search-input">
    </div>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>
  <div id="search-result"></div>
</div>


  </div>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="localhost:4000/2019/08/16/Scrapy爬取CSDN博客列表/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="钟浩伟">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/profile.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="钟浩伟的个人博客">
    </span>
      <header class="post-header">

        
          <h1 class="post-title" itemprop="name headline">Scrapy爬取CSDN博客列表

            
          </h1>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-08-16 13:48:43" itemprop="dateCreated datePublished" datetime="2019-08-16T13:48:43+08:00">2019-08-16</time>
            </span>
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>Scrapy是一个为了爬取网站数据，提取结构性数据而编写的应用框架。 其可以应用在数据挖掘，信息处理或存储历史数据等一系列的程序中。其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的， 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛，可以用于数据挖掘、监测和自动化测试。</p>
<p>具体可查看文档 <a href="https://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/overview.html" title="scrapy中文文档" target="_blank" rel="noopener">scrapy中文文档</a></p>
<a id="more"></a>

<p><img src="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816235500.png!blog" alt="20190816235500"></p>
<h1 id="新建Scrapy爬虫项目"><a href="#新建Scrapy爬虫项目" class="headerlink" title="新建Scrapy爬虫项目"></a>新建Scrapy爬虫项目</h1><p>如果你还没有安装Scrapy，可以通过下面这个命令安装</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install scrapy</span><br></pre></td></tr></table></figure>

<h2 id="新建一个项目"><a href="#新建一个项目" class="headerlink" title="新建一个项目"></a>新建一个项目</h2><p>安装好之后就可以创建项目了</p>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">scrapy </span>startproject 你的项目名</span><br></pre></td></tr></table></figure>

<p><img src="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816135546.png!blog" alt="20190816135546"></p>
<p>创建好之后的目录如上图所示</p>
<p>每个文件的具体作用可以参照Scrapy的官方文档，这里就不再赘述。</p>
<h2 id="新建一个爬虫"><a href="#新建一个爬虫" class="headerlink" title="新建一个爬虫"></a>新建一个爬虫</h2><p>通过命令</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">scrapy genspider 你的爬虫名</span><br></pre></td></tr></table></figure>

<p><img src="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816140048.png!blog" alt="20190816140048"></p>
<h1 id="设置配置文件"><a href="#设置配置文件" class="headerlink" title="设置配置文件"></a>设置配置文件</h1><p>如果你不需要存入数据库或者做进一步的反爬处理，则可以跳过这一步，打开setting.py进行以下修改</p>
<h2 id="设置浏览器名"><a href="#设置浏览器名" class="headerlink" title="设置浏览器名"></a>设置浏览器名</h2><p>把BOT_NAME设置为你的浏览器名，如果使用默认，别人一看就知道是爬虫</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">BOT_NAME = <span class="string">'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'</span></span><br></pre></td></tr></table></figure>

<h2 id="设置日志级别"><a href="#设置日志级别" class="headerlink" title="设置日志级别"></a>设置日志级别</h2><p>这样就不需要打印太多日志信息，干扰视线</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LOG_LEVEL=<span class="string">'WARN'</span></span><br></pre></td></tr></table></figure>

<h2 id="设置模式"><a href="#设置模式" class="headerlink" title="设置模式"></a>设置模式</h2><p>将机器人模式设为FALSE</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">ROBOTSTXT_OBEY</span> = <span class="literal">False</span></span><br></pre></td></tr></table></figure>

<h2 id="设置你要抓取的博客页数"><a href="#设置你要抓取的博客页数" class="headerlink" title="设置你要抓取的博客页数"></a>设置你要抓取的博客页数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#博客页数</span></span><br><span class="line">CsdnPage = <span class="number">2</span>;</span><br></pre></td></tr></table></figure>

<h2 id="设置你的数据库"><a href="#设置你的数据库" class="headerlink" title="设置你的数据库"></a>设置你的数据库</h2><p>为了方便将数据自动导入数据库，需要设置数据库配置信息，我使用的是mysql</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#数据库设置</span></span><br><span class="line">MYSQL_HOST = <span class="string">'你的主机名'</span></span><br><span class="line">MYSQL_PORT = <span class="number">3306</span> <span class="comment">#端口</span></span><br><span class="line">MYSQL_DBNAME = <span class="string">'DBNAME'</span> <span class="comment"># 数据库名</span></span><br><span class="line">MYSQL_TABLE = <span class="string">'TABLE_NAME'</span> <span class="comment">#表名</span></span><br><span class="line">MYSQL_USER = <span class="string">'你的用户名'</span> </span><br><span class="line">MYSQL_PASSWD=<span class="string">'你的密码'</span></span><br></pre></td></tr></table></figure>

<h1 id="新建数据项"><a href="#新建数据项" class="headerlink" title="新建数据项"></a>新建数据项</h1><p>数据项的作用是方便scrapy以结构化的数据插入到数据库中。</p>
<p>打开 items.py，复制一下代码即可，或者你如果要爬新的数据，请记得加入新的字段</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> scrapy</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CsdnItem</span><span class="params">(scrapy.Item)</span>:</span></span><br><span class="line">    <span class="comment"># define the fields for your item here like:</span></span><br><span class="line">    title = scrapy.Field()</span><br><span class="line">    url = scrapy.Field()</span><br><span class="line">    <span class="comment">#date = scrapy.Field()</span></span><br><span class="line">    tag = scrapy.Field()</span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>

<h1 id="编写爬虫文件"><a href="#编写爬虫文件" class="headerlink" title="编写爬虫文件"></a>编写爬虫文件</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">import scrapy</span><br><span class="line">from ..items import CsdnItem</span><br><span class="line">from ..settings import CsdnPage</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class CsdnSpiderSpider(scrapy.Spider):</span><br><span class="line">    name = &apos;csdn_spider&apos;</span><br><span class="line">    allowed_domains = [&apos;blog.csdn.net&apos;]</span><br><span class="line">    start_urls = [&apos;https://blog.csdn.net/weixin_41154636/article/list/1&apos;]</span><br><span class="line"></span><br><span class="line">    def parse(self, response):</span><br><span class="line">        try:</span><br><span class="line">            for div in response.xpath(&apos;//div[contains(@class,&quot;article-item-box&quot;)]&apos;):</span><br><span class="line">                item = CsdnItem()</span><br><span class="line">                item[&apos;title&apos;] = div.xpath(&apos;./h4/a/text()&apos;)[1].extract().strip()</span><br><span class="line">                item[&apos;url&apos;] = div.xpath(&apos;./h4/a/@href&apos;)[0].extract().strip()</span><br><span class="line">                item[&apos;tag&apos;] = item[&apos;url&apos;].split(&apos;/&apos;)[-1]  # 爬取时间戳，方便按时间排序</span><br><span class="line">                # item[&apos;date&apos;] = div.xpath(&apos;//span[@class=&quot;date&quot;]/text()&apos;)[1].extract().strip()</span><br><span class="line">                # 我也不知道为什么抓出来会有这个- -，所以特殊处理一下</span><br><span class="line">                if item[&apos;title&apos;] == &apos;帝都的凛冬&apos;:</span><br><span class="line">                    continue</span><br><span class="line">                # 控制台输出</span><br><span class="line">                print(item[&apos;title&apos;] + &quot; &quot; + item[&apos;url&apos;] + &quot; &quot; + item[&apos;tag&apos;])</span><br><span class="line">                # 封装成bean，装入数据库</span><br><span class="line">                yield item</span><br><span class="line">                # 实现翻页的功能</span><br><span class="line">                for page in range(2, CsdnPage + 1):</span><br><span class="line">                    url = &quot;https://blog.csdn.net/weixin_41154636/article/list/%s&quot; % page</span><br><span class="line">                    yield scrapy.Request(url, callback=self.parse)</span><br><span class="line">        except BaseException:</span><br><span class="line">            print(BaseException.__cause__)</span><br><span class="line"></span><br><span class="line">    pass</span><br></pre></td></tr></table></figure>

<p>具体代码的说明注释已经写得很清楚了。</p>
<p>另外，需要注意的是，因为CSDN的翻页是通过ajax请求实现的，所以需要自己构造请求。</p>
<p>如果发现跑不起来，很可能是因为CSDN的HTML结构发生了改变，你可以了解一下XPATH的写法，然后修改即可。</p>
<p>先看下运行结果吧：</p>
<p>进入到spiders目录中运行</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">scrapy crawl csdn_spider <span class="comment">#你的爬虫名，在上面的代码最开始定义的</span></span><br></pre></td></tr></table></figure>

<p><img src="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816145051.png!blog" alt="20190816145051"></p>
<p>DONE！信息已经爬下来了，接下来就是把数据保存至数据库中。</p>
<h1 id="保存数据至数据库"><a href="#保存数据至数据库" class="headerlink" title="保存数据至数据库"></a>保存数据至数据库</h1><p>在setting.py中，把pipeline注释去掉</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ITEM_PIPELINES = &#123;</span><br><span class="line">   <span class="string">'csdn.pipelines.CsdnPipeline'</span>: <span class="number">300</span>,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在piplines.py中编写一下代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"><span class="keyword">from</span> scrapy.utils.project <span class="keyword">import</span> get_project_settings</span><br><span class="line"><span class="keyword">from</span> twisted.enterprise <span class="keyword">import</span> adbapi</span><br><span class="line"><span class="keyword">from</span> .items <span class="keyword">import</span> CsdnItem</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DBHelper</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.settings = get_project_settings()  <span class="comment"># 获取settings配置数据</span></span><br><span class="line">        dbparams = dict(</span><br><span class="line">            host=self.settings[<span class="string">'MYSQL_HOST'</span>],  <span class="comment"># 读取settings中的配置</span></span><br><span class="line">            db=self.settings[<span class="string">'MYSQL_DBNAME'</span>],</span><br><span class="line">            user=self.settings[<span class="string">'MYSQL_USER'</span>],</span><br><span class="line">            passwd=self.settings[<span class="string">'MYSQL_PASSWD'</span>],</span><br><span class="line">            charset=<span class="string">'utf8'</span>,  <span class="comment"># 编码要加上，否则可能出现中文乱码问题</span></span><br><span class="line">            cursorclass=pymysql.cursors.DictCursor,</span><br><span class="line">            use_unicode=<span class="literal">False</span>,</span><br><span class="line">        )</span><br><span class="line">        <span class="comment"># **表示将字典扩展为关键字参数,相当于host=xxx,db=yyy....</span></span><br><span class="line">        dbpool = adbapi.ConnectionPool(<span class="string">'pymysql'</span>, **dbparams)</span><br><span class="line">        self.dbpool = dbpool</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">connect</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.dbpool</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 插入数据</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">insert</span><span class="params">(self, item)</span>:</span></span><br><span class="line">        self.settings = get_project_settings()  <span class="comment"># 获取settings配置数据</span></span><br><span class="line">        <span class="keyword">if</span> isinstance(item, CsdnItem):</span><br><span class="line">            tb_name = self.settings[<span class="string">'MYSQL_TABLE'</span>]</span><br><span class="line">            sql = <span class="string">"""insert into """</span> + tb_name + <span class="string">"""(id,title,link) values (%s,%s,%s) """</span></span><br><span class="line">            <span class="comment"># print(sql)</span></span><br><span class="line">            <span class="comment"># 调用插入的方法</span></span><br><span class="line">            query = self.dbpool.runInteraction(self._conditional_insert, sql, item)</span><br><span class="line">            <span class="comment"># 调用异常处理方法</span></span><br><span class="line">            query.addErrback(self._handle_error)</span><br><span class="line">            <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 写入数据库中</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_conditional_insert</span><span class="params">(self, canshu, sql, item)</span>:</span></span><br><span class="line">        <span class="comment"># 取出要存入的数据，这里item就是爬虫代码爬下来存入items内的数据</span></span><br><span class="line">        <span class="keyword">if</span> isinstance(item, CsdnItem):</span><br><span class="line">            <span class="keyword">import</span> datetime</span><br><span class="line">            <span class="comment"># 字符串转为DateTime类型</span></span><br><span class="line">            <span class="comment"># dateTime_p = datetime.datetime.strptime(item['date'], '%Y-%m-%d %H:%M:%S')</span></span><br><span class="line">            params = (</span><br><span class="line"></span><br><span class="line">                item[<span class="string">'tag'</span>], item[<span class="string">'title'</span>], item[<span class="string">'url'</span>])</span><br><span class="line">            canshu.execute(sql, params)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 错误处理方法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_handle_error</span><span class="params">(self, failue)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">        print(<span class="string">'--------------database operation exception!!-----------------'</span>)</span><br><span class="line">        <span class="comment"># self.connect.rollback()</span></span><br><span class="line">        print(failue)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 这里执行scrapy处理脚本</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CsdnPipeline</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.db = DBHelper()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_item</span><span class="params">(self, item, spider)</span>:</span></span><br><span class="line">        <span class="comment"># 插入数据库</span></span><br><span class="line">        self.db.insert(item)</span><br><span class="line">        <span class="keyword">return</span> item</span><br></pre></td></tr></table></figure>

<p>具体说明注释已经写的很清楚了。</p>
<p>这样就完成了导入至数据库的工作</p>
<p>再次运行爬虫。</p>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">scrapy </span>crawl csdn_spider</span><br></pre></td></tr></table></figure>

<p>可以看到，数据就全部自动导入到数据库了！</p>
<p><img src="https://zhong-blog.oss-cn-shenzhen.aliyuncs.com/blog/20190816145728.png!blog" alt="20190816145728"></p>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="\2019\06\01\Python爬虫：基于Scrapy的爬取失踪人口数据小爬虫\" rel="bookmark">Python爬虫：基于Scrapy的爬取失踪人口数据小爬虫</a></div>
      
    </li>
  
  </ul>


    
    <div>
      
      <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束感谢您的阅读,如有疑问，请联系<a href="mailto:610596547@qq.com">610596547@qq.com</a>-------------</div>
    
</div>
      
    </div>
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/爬虫/" rel="tag"># 爬虫</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/08/14/计算机组成原理：系统总线总结/" rel="next" title="计算机组成原理：系统总线总结">
                  <i class="fa fa-chevron-left"></i> 计算机组成原理：系统总线总结
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/08/16/hexo部署云服务器的全过程/" rel="prev" title="hexo部署云服务器的全过程">
                  hexo部署云服务器的全过程 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/profile.jpg"
      alt="钟浩伟">
  <p class="site-author-name" itemprop="name">钟浩伟</p>
  <div class="site-description motion-element" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">44</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/XiaoZhong233" title="GitHub &rarr; https://github.com/XiaoZhong233" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:601596547@qq.com" title="E-Mail &rarr; mailto:601596547@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://blog.csdn.net/weixin_41154636" title="CSDN &rarr; https://blog.csdn.net/weixin_41154636" rel="noopener" target="_blank"><i class="fa fa-fw fa-book"></i>CSDN</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="http://profile.zhonghaowei.xyz/" title="Profile &rarr; http://profile.zhonghaowei.xyz/" rel="noopener" target="_blank"><i class="fa fa-fw fa-address-card-o"></i>Profile</a>
      </span>
    
  </div>



        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#新建Scrapy爬虫项目"><span class="nav-number">2.</span> <span class="nav-text">新建Scrapy爬虫项目</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#新建一个项目"><span class="nav-number">2.1.</span> <span class="nav-text">新建一个项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#新建一个爬虫"><span class="nav-number">2.2.</span> <span class="nav-text">新建一个爬虫</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#设置配置文件"><span class="nav-number">3.</span> <span class="nav-text">设置配置文件</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#设置浏览器名"><span class="nav-number">3.1.</span> <span class="nav-text">设置浏览器名</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置日志级别"><span class="nav-number">3.2.</span> <span class="nav-text">设置日志级别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置模式"><span class="nav-number">3.3.</span> <span class="nav-text">设置模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置你要抓取的博客页数"><span class="nav-number">3.4.</span> <span class="nav-text">设置你要抓取的博客页数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置你的数据库"><span class="nav-number">3.5.</span> <span class="nav-text">设置你的数据库</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#新建数据项"><span class="nav-number">4.</span> <span class="nav-text">新建数据项</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#编写爬虫文件"><span class="nav-number">5.</span> <span class="nav-text">编写爬虫文件</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#保存数据至数据库"><span class="nav-number">6.</span> <span class="nav-text">保存数据至数据库</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      



    </div>
  </aside>
  <div id="sidebar-dimmer"></div>




      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钟浩伟</span>
</div>


<div id="days"></div>
<div class="BbeiAn-info">
   	粤ICP备 -
    <a target="_blank" href="http://beian.miit.gov.cn" style="color:#f0d784"  rel="nofollow">粤ICP备19111001号-1</a> <!--a标签中增加nofollow属性，避免爬虫出站。-->| 
	<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=" style="color:#f0d784;text-decoration:none;padding-left:30px;background:url(https://s1.ax1x.com/2018/09/29/ilmwIH.png) no-repeat left center" rel="nofollow">粤公网安备 粤ICP备19111001号-1</a>	  <!--这里将图标作为了背景，以使得能和后面的文字在同一行-->
</div>

<script>
function show_date_time(){
    window.setTimeout("show_date_time()", 1000);
    BirthDay=new Date("08/15/2019 22:40:14");
    today=new Date();
    timeold=(today.getTime()-BirthDay.getTime());
    sectimeold=timeold/1000
    secondsold=Math.floor(sectimeold);
    msPerDay=24*60*60*1000
    e_daysold=timeold/msPerDay
    daysold=Math.floor(e_daysold);
    e_hrsold=(e_daysold-daysold)*24;
    hrsold=setzero(Math.floor(e_hrsold));
    e_minsold=(e_hrsold-hrsold)*60;
    minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
    seconds=setzero(Math.floor((e_minsold-minsold)*60));
    document.getElementById('days').innerHTML="<p>小破站已运行 "+daysold+" 天 "+hrsold+" 小时 "+minsold+" 分 "+seconds+" 秒</p>";
}
function setzero(i) {
    if (i<10) {
        i="0" + i
    };
    return i;
}
show_date_time();
</script>

        








        
      </div>
    </footer>
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>

    

  </div>

  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>

<script src="/js/schemes/pisces.js?v=7.3.0"></script>



<script src="/js/next-boot.js?v=7.3.0"></script>




  















  <script src="/js/local-search.js?v=7.3.0"></script>










<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme: 'default',
      logLevel: 3,
      flowchart: { curve: 'linear' },
      gantt: { axisFormat: '%m/%d/%Y' },
      sequence: { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>




  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>



  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":false}});</script></body>
</html>
